const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.role = this.model("system/role");
		this.unit = this.model("system/unit");
		this.rule = this.model("system/rule");
		this.user = this.model("system/user");
		this.role_rule = this.model('system/role_rule');
		this.user_role = this.model("system/user_role");

	}
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		let unit_id = posts.unitid || 0;
		let where = {};
		if(unit_id > 0) {
			where.unit_id = unit_id;
		}
		const data = await this.role.dataTable(posts, where);
		return this.json(data);

	}

	async treeAction() {

		let pid = this.get("pid");

		let units = await this.unit.getChilds(pid);
		let data = [];
		if(!pid) {
			data = [{
				id: '0',
				text: '所有角色',
				children: 0
			}];

		}

		if(!think.isEmpty(units)) {

			units.forEach(function(o) {
				let unit = {};
				unit.id = o.id;
				unit.text = o.name;
				unit.children = o.hasChildren == 1 ? true : false;
				data.push(unit);
			});

		}

		return this.json(data);

	}

	async addAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();

		let code = posts.code;
		let role = await this.role.where({
			code: code
		}).find();

		if(!think.isEmpty(role)) {
			return this.fail("权限标识已存在");
		}

		let user = await this.session("user");

		let time = new Date().valueOf();
		let role_id = await this.role.add({
			name: posts.name,
			code: code,
			status: posts.disabled ? 0 : 1,
			created_by: user.id,
			create_time: time,
			unit_id: posts.unitid

		});
		if(role_id == 0) {
			return this.fail("添加失败");
		}

		role = await this.role.findOne(role_id);
		if(!think.isEmpty(role) && posts.menuIds) {

			let rules = posts.menuIds.split(',');
			let roleRule = [];
			rules.forEach(function(rule) {
				roleRule.push({
					role_id: role.id,
					rule_id: rule
				});
			});

			await this.role_rule.addMany(roleRule);

		}

		return this.success("添加成功");

	}

	async ruleTreeAction() {

		let pid = this.get("pid");
		let rules = await this.rule.getChilds(pid);
		let str = [];
		if(!think.isEmpty(rules)) {
			rules.forEach(function(o) {
				let obj = {};
				obj.id = o.id;
				obj.text = o.name;
				obj.children = o.hasChildren == 1 ? true : false;
				obj.icon = o.icon;
				obj.data = o.url || '';
				str.push(obj);
			});
		}
		return this.json(str);
	}

	async editAction() {

		if(this.isGet) {

			let id = this.get("id");

			let role = await this.role.findOne(id);
			if(think.isEmpty(role.unit)) {
				role.unit = {
					name: "系统角色",
					id: 0
				}
			}

			this.assign("role", role);

			return this.display();

		}

		let posts = this.post();

		let oldcode = posts.old_code;
		let code = posts.code;

		if(code != oldcode) {
			let role = await this.role.where({
				code: code
			}).find();
			if(!think.isEmpty(role)) {
				return this.fail("权限标识已存在");
			}

		}

		let rows = await this.role.setOne(posts.id, {
			name: posts.name,
			unit_id: posts.unitid,
			code: code
		});
		if(rows == 0) {
			return this.fail("修改失败");
		}
		return this.success("修改成功");

	}

	async deleteAction() {

		let ids = this.post("id") || JSON.parse(this.post("ids"));
		console.log(ids)
		let rows = await this.role.where({
			id: ['IN', ids]
		}).setRelation(false).delete();
		if(rows == 0) {
			return this.fail("删除失败");
		}
		return this.success("删除成功");

	}

	async statusAction() {

		let id = this.post("id");
		let status = this.post("status");
		let row = await this.role.setOne(id, {
			status: this.post("status")
		});

		if(row == 0) {
			return this.fail("修改失败");
		}

		return this.success();

	}

	async ruleAction() {
		let roleid = this.get("id");

		let permission = await this.role.permission(roleid);

		this.assign("role", permission.role);
		this.assign("roleFirstMenus", permission.firstMenus);
		this.assign("roleSecondMenus", JSON.stringify(permission.secondMenus));
		return this.display();

	}

	async editRuleAction() {

		if(this.isGet) {
			let roleid = this.get("id");
			let rules = await this.rule.order("sort asc").select();
			let str = [];
			if(!think.isEmpty(rules)) {
				rules.forEach(function(o) {
					var obj = {};
					obj.id = o.id;
					obj.text = o.name;
					obj.icon = o.icon;
					obj.data = o.url || '';
					obj.parent = o.pid == 0 ? "#" : o.pid;
					str.push(obj);
				});

			}

			this.assign("roleid", roleid);
			this.assign("menu", JSON.stringify(str));
			return this.display();

		}

		let ids = JSON.parse(this.post("ids"));
		let roleid = this.post("roleid");

		let role = await this.role.findOne(roleid);
		if(!think.isEmpty(role) && ids) {

			await this.role_rule.where({
				role_id: roleid
			}).delete();
			let roleRule = [];
			ids.forEach((rule) => {
				roleRule.push({
					role_id: role.id,
					rule_id: rule
				});
			});

			await this.role_rule.addMany(roleRule);

		}

		return this.success("添加成功");

	}
	async editUserAction() {

		if(this.isGet) {
			let roleid = this.get("id");
			let role = await this.role.findOne(roleid);
			this.assign("role", role)

			return this.display();
		}

		let posts = this.post();
		let roleid = posts.roleid || 0;
		let username = posts.username;
		let nickname = posts.nickname;

		let where = {};

		if(!think.isEmpty(username)) {
			where.username = ['like', '%' + username + '%'];
		}
		if(!think.isEmpty(nickname)) {
			where.nickname = ['like', '%' + nickname + '%'];

		}

		let userRole = await this.user_role.where({
			role_id: roleid
		}).select();

		let userids = [];

		userRole.forEach(function(u) {
			userids.push(u.user_id);
		});

		if(userids.length > 0) {
			where.id = ['IN', userids];

		}

		const data = await this.dataTable(posts, where, this.user);
		return this.json(data);
	}

	async selectUserAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		let roleid = posts.roleid || 0;
		let sort = {};
		let where = {};

		if(!think.isEmpty(posts.name)) {
			where = {
				'username|nickname': ['like', '%' + posts.name + '%']
			};
		}

		let userRole = await this.user_role.where({
			role_id: roleid
		}).select();

		let userids = [];

		userRole.forEach(function(u) {
			userids.push(u.user_id);
		});

		if(userids.length > 0) {
			where.id = ['NOTIN', userids];
		}
		const data = await this.dataTable(posts, where, this.user);
		return this.json(data);
	}

	async pushUserAction() {

		let posts = this.post();
		let ids = JSON.parse(posts.ids);

		let role = await this.role.findOne(posts.roleid);

		if(!think.isEmpty(role) && !think.isEmpty(ids)) {
			let roleUser = [];
			ids.forEach(function(userid) {
				roleUser.push({
					role_id: role.id,
					user_id: userid
				});
			});

			await this.user_role.addMany(roleUser);
			return this.success("添加成功");

		} else {
			return this.fail("添加失败");
		}

	}

	async delUserAction() {

		let posts = this.post();
		let ids = JSON.parse(posts.ids);

		let role = await this.role.findOne(posts.roleid);

		if(!think.isEmpty(role) && !think.isEmpty(ids)) {

			await this.user_role.where({
				role_id: role.id,
				user_id: ['IN', ids]
			}).delete();
			return this.success("删除成功");

		} else {
			return this.fail("删除失败");
		}

	}

};